<?php

/**
 * DoctorAssistant form.
 *
 * @package    docplus.co.za
 * @subpackage form
 * @author     Fox Matuku
 * @version    SVN: $Id: sfDoctrineFormTemplate.php 23810 2009-11-12 11:07:44Z Kris.Wallsmith $
 */
class DoctorAssistantForm extends BaseDoctorAssistantForm {
	private $requiredFields = array('email');

	public function configure() {
		unset(
			$this['created_at'], $this['updated_at']
		);

		// grab the gender generated options
		$genderOptions = $this->widgetSchema['gender']->getOptions("choices");

		$this->widgetSchema['user_id'] = new sfWidgetFormInputHidden();
		$this->widgetSchema['doctor_id'] = new sfWidgetFormInputHidden();
		$this->widgetSchema['first_name'] = new sfWidgetFormInputText(array(), array("autocomplete" => "off"));
		$this->widgetSchema['last_name'] = new sfWidgetFormInputText(array(), array("autocomplete" => "off"));
		$this->widgetSchema['gender']->setOption("choices", array_merge(array("" => "Please select a gender"), $genderOptions["choices"]));
		$this->widgetSchema["gender"]->setAttribute("class", "select-box-small");
		$this->widgetSchema['language_id']->setOption("add_empty", "Please select a language");
		$this->widgetSchema["language_id"]->setAttribute("class", "select-box-small");
		$this->widgetSchema['email'] = new sfWidgetFormInputText(array(), array("autocomplete" => "off"));
		$this->widgetSchema['password'] = new sfWidgetFormInputPassword(array(), array("autocomplete" => "off"));
		$this->widgetSchema['password_confirm'] = clone $this->widgetSchema['password'];
		$this->widgetSchema['password_confirm']->setLabel("Confirm password");
		$this->widgetSchema['is_active'] = new sfWidgetFormInputCheckbox();

		$this->validatorSchema['user_id'] = new sfValidatorString(array('required' => false));
		$this->validatorSchema['first_name'] = new sfValidatorString(array('max_length' => 255, 'required' => true), array('required' => 'Your *first name* is required.'));
		$this->validatorSchema['last_name'] = new sfValidatorString(array('max_length' => 255, 'required' => true), array('required' => 'Your *last name* is required.'));
		$this->validatorSchema['gender'] = new sfValidatorString(array('max_length' => 255, 'required' => true), array('required' => 'Your *gender* is required.'));
		$this->validatorSchema['language_id'] = new sfValidatorString(array('max_length' => 255, 'required' => true), array('required' => 'Your *language* is required.'));
		$this->validatorSchema['email'] = new sfValidatorEmail(array("required" => true), array("invalid" => "Your *email* is invalid.", "required" => "Your *email* is required email."));
		$this->validatorSchema['password'] = new sfValidatorString(array('required' => true, 'max_length' => 128, 'required' => $this->getObject()->isNew()), array('required' => 'Your *password* is required.'));
		$this->validatorSchema['password_confirm'] = clone $this->validatorSchema['password'];
		$this->validatorSchema['password_confirm']->setMessage('required', 'Your *confirm password* is required.');
		$this->validatorSchema['is_active'] = new sfValidatorBoolean(array('required' => false));
		$this->validatorSchema->setPostValidator(new sfValidatorCallback(array('callback' => array($this, '_emailAlreadyExistsValidator'))));
		$this->mergePostValidator(new sfValidatorSchemaCompare('password', sfValidatorSchemaCompare::EQUAL, 'password_confirm', array(), array('invalid' => 'Your *two passwords* must be the same.')));

		$this->setDefaults(array(
			"first_name" => $this->getObject()->getFirstName(),
			"last_name" => $this->getObject()->getLastName(),
			"email" => $this->getObject()->getEmail(),
			"is_active" => $this->getObject()->getIsActive()
		));
	}

	public function _emailAlreadyExistsValidator($validator, $values, $arguments) {
		foreach ($this->requiredFields as $field) {
			try {
				$this->validatorSchema[$field]->clean($values[$field]);
			}
			catch (sfValidatorErrorSchema $e) {
				return $values;
			}
			catch (sfValidatorError $e) {
				return $values;
			}
		}

		// try to fetch the supplied email
		$gfUser = GfUserTable::getInstance()->findOneByEmail($values['email']);

		// check for the existence of a user with this email
		if (is_object($gfUser) && $gfUser->getId() != $values["user_id"]) {
			$this->validatorSchema['email']->setMessage('invalid', 'This email already exists.');
		}
		else {
			return $values;
		}

		// since we've reached here seems the supplied email exists already
		throw new sfValidatorErrorSchema($this->validatorSchema['email'], array('email' => new sfValidatorError($this->validatorSchema['email'], 'invalid')));
		return $values;
	}

	/**
	 * Override the save method to save the merged user form.
	 */
	public function save($con = null) {
		$this->updateUser();
		return parent::save($con);
	}

	/**
	 * Updates the user merged form
	 */
	protected function updateUser() {
		if (!is_null($user = $this->getUser())) {
			if (!$user->getId()) {
				$user->setAlgorithm('md5');
				$user->setType("Assistant");
			}
			$user->setFirstName($this->getValue("first_name"));
			$user->setLastName($this->getValue("last_name"));
			$user->setEmail($this->getValue("email"));
			$password = $this->getValue("password");
			if (!empty($password)) $user->setPassword($password);
			$user->setIsActive($this->getValue("is_active"));
			$user->save();

			unset($this->values['first_name'], $this->values['last_name'], $this->values['email'], $this->values['password'], $this->values['password_confirm'], $this->values['user_id']);

			// set the user id
			$this->values['user_id'] = $user->get('id');
		}
	}

	/**
	 * Returns the user object. If it does not exist return a new instance.
	 *
	 * @return sfGuardUser
	 */
	protected function getUser() {
		if (!$this->getObject()->getUser()) {
			return new GfUser();
		}

		return $this->getObject()->getUser();
	}

}
